/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.jueb.socks5;

import java.util.HashMap;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;

public final class SocksServer {


    public void run(HashMap<String,String> config){
    	
    	int port=1080;
    	if(config.containsKey("port"))
    	{
    		try {
				port=Integer.parseInt(config.get("port"));
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
        System.err.println("Listening on*:" + port + "...");
        EventLoopGroup bossGroup = new NioEventLoopGroup();//主线程池
        EventLoopGroup workerGroup = new NioEventLoopGroup();//从线程池
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, false);//设置不保持连接
        b.childHandler(new SocksServerInitializer(config));
        try {
        	Channel channel=b.bind(port).sync().channel();
        	System.out.println("代理服务器启动成功,地址："+channel.localAddress().toString());
        	channel.closeFuture().sync();
        	System.out.println("代理服务器关闭!");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
        	//如果出现错误，则关闭主从线程池
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
       
      
    }
}
